import React, { useEffect, useState } from 'react'
import Taro, { FC, useRouter } from '@tarojs/taro'
import { useSelector } from 'react-redux'
import { View, Text, ScrollView, Button } from '@tarojs/components'
import { AtInput, AtListItem, AtFloatLayout, AtIcon } from 'taro-ui'
import { AddressObj } from '@/constants/commonType'
import api from '@/services/config/index'
import './editAndDelete.scss'

type PageStateProps = {
  type: string
}
type nowAddress = Array<{
  id: string
  name: string
  isDelete?: string
  level?: string
  pid?: string
  createAt?: null | string
}>
type cacheAddress = Array<nowAddress>

interface FormValue {
  action: 1 | 2 | 3
  // 选择地址的一级
  streetId: string
  // 选择地址的二级
  communityId: string
  // 选择地址的三级
  districtId: string
  // 选择地址的四级
  areaAddressId: string
  address?: string
  // 详细地址
  addressDetail: string
  // 联系人
  addressName: string
  // 手机号码
  addressMobile: string
  state: 1 | 0
  // 地址id
  addressId?: string
}
type useSelectorState = {
  address: AddressObj
}
const EditAndDelete: FC<PageStateProps> = () => {
  const address = useSelector((state: useSelectorState) => state.address)
  const [formValue, setFormValue] = useState<FormValue>({
    action: 1,
    streetId: '',
    communityId: '',
    districtId: '',
    areaAddressId: '',
    addressDetail: '',
    addressName: '',
    addressMobile: '',
    state: 0,
    address: '',
    addressId: ''
  })
  const [selectResult, setSelectResult] = useState<nowAddress>([]) //选择结果
  const [nowAddress, setNowAddress] = useState<nowAddress>([]) // 当前选择列表
  const [cacheAddress, setCacheAddress] = useState<cacheAddress>([]) // 缓存列表
  const [isOpened, setIsOpened] = useState<boolean>(false)
  const router = useRouter()
  const { type } = router.params
  // 获取固定地址
  function getAddress() {
    api['address/getAddress']().then((res) => {
      setNowAddress(res.data)
      setCacheAddress([...cacheAddress, ...[res.data]])
    })
  }
  // 表单验证
  function formValidation() {
    const { addressName, addressMobile, streetId, addressDetail } = formValue
    return [
      {
        judgeKey: addressName,
        tips: '请输入收货人姓名'
      },
      {
        judgeKey: addressMobile,
        tips: '请输入手机号码'
      },
      {
        judgeKey: streetId,
        tips: '请输入关联小区'
      },
      {
        judgeKey: addressDetail,
        tips: '请输入详细地址'
      }
    ]
  }
  // 添加地址
  function addAddress() {
    const _formValidation = formValidation()
    let flag = false
    for (const item of _formValidation) {
      if (!item.judgeKey) {
        flag = true
        Taro.showToast({
          title: item.tips,
          icon: 'none'
        })
        break
      }
    }
    if (flag) return
    api['address/addAddress'](formValue).then((_) => {
      Taro.showToast({
        title: type === 'edit' ? '编辑成功' : '添加成功',
        icon: 'none'
      })
      Taro.navigateBack({ delta: 1 })
    })
  }

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: type === 'edit' ? '编辑地址' : '添加地址'
    })
    if (type === 'edit') {
      setFormValue({
        ...formValue,
        action: 2,
        addressName: address.addressName,
        addressMobile: address.addressMobile,
        addressDetail: address.addressDetail,
        streetId: address.street.streetId,
        communityId: address.community.communityId,
        districtId: address.district.districtId,
        areaAddressId: address.areaAddress.areaAddressId,
        addressId: address.addressId
      })
    }

    getAddress()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 表单监视
  function handleChange(value, e) {
    const name = e.target.id
    const _formValue = Object.assign({}, formValue)
    _formValue[name] = value
    setFormValue(_formValue)
  }

  // 选择关联小区列表
  function selectAddress(item) {
    const selectResultLen = selectResult.length
    const _selectResult = selectResult.slice()
    const level = item.level - 1
    if (level > selectResultLen) {
      _selectResult.push(item)
    } else if (level === selectResultLen) {
      _selectResult[level - 1] = item
    }
    setSelectResult(_selectResult)
    if (item.child.length > 0) {
      const _cacheAddress = cacheAddress
      _cacheAddress.push(item.child)
      setCacheAddress(_cacheAddress)
      setNowAddress(item.child)
    }
  }
  // 点击以选中的关联小区列表
  function recallAddress(key) {
    const _cacheAddress = cacheAddress[key]
    const _selectResult = selectResult.slice(0, key + 1)
    setSelectResult(_selectResult)
    setNowAddress(_cacheAddress)
  }
  function village() {
    let str = ''
    selectResult.map((item) => {
      str += item.name
    })
    return str
  }
  function onClose() {
    setFormValue({
      ...formValue,
      streetId: selectResult[0] && selectResult[0].id,
      communityId: selectResult[1] && selectResult[1].id,
      districtId: selectResult[2] && selectResult[2].id,
      areaAddressId: selectResult[3] && selectResult[3].id
    })
    setIsOpened(false)
  }

  function chooseLocation() {
    Taro.chooseLocation({
      success(item) {
        console.log(666, item)
        setFormValue({
          ...formValue,
          addressDetail: item.address
        })
      }
    })
  }
  return (
    <View className='addAddress grey-bgc'>
      <View className='container white-bgc'>
        {/* 收货人 */}
        <View className='addAddress-receiver'>
          <AtInput
            value={formValue.addressName}
            name='addressName'
            title='收货人：'
            placeholderClass='classify-placeolder'
            placeholder='请输入收货人姓名'
            onChange={handleChange}
          ></AtInput>
        </View>
        {/* 手机号码 */}
        <View className='addAddress-phone'>
          <AtInput
            name='addressMobile'
            value={formValue.addressMobile}
            type='phone'
            title='手机号码：'
            placeholderClass='classify-placeolder'
            placeholder='请输入手机号码'
            onChange={handleChange}
          ></AtInput>
        </View>
        {/* 关联小区 */}
        <View
          className='addAddress-village'
          onClick={() => {
            setIsOpened(true)
          }}
        >
          <AtListItem title='关联小区' note={village()} arrow='right' />
        </View>
        {/* 详细地址 */}
        <View className='addAddress-detail'>
          <AtInput
            name='addressDetail'
            value={formValue.addressDetail}
            title='详细地址'
            placeholderClass='classify-placeolder'
            placeholder='请输入详细地址'
            onChange={handleChange}
          ></AtInput>
          <View className='addAddress-detail__icon' onClick={chooseLocation}>
            <AtIcon value='map-pin' size='25' color='#bbbbbb'></AtIcon>
          </View>
        </View>
      </View>
      {/* 关联小区弹窗 */}
      <AtFloatLayout isOpened={isOpened} title='请选择' onClose={onClose}>
        <View className='select-result b-bottom'>
          选择结果：
          {selectResult.map((item, key) => {
            return (
              <Text
                key={item.id}
                className='select-result__txt'
                onClick={() => {
                  recallAddress(key)
                }}
              >
                {item.name}
              </Text>
            )
          })}
        </View>
        <View className='select-address'>
          <ScrollView
            className='scrollview'
            scrollY
            scrollWithAnimation
            scrollTop={0}
            style={{ height: '200px' }}
            lowerThreshold={20}
            upperThreshold={20}
          >
            {nowAddress.map((item) => {
              return (
                <View
                  key={item.id}
                  onClick={selectAddress.bind(null, item)}
                  className='select-address__txt'
                >
                  {item.name}
                </View>
              )
            })}
          </ScrollView>
        </View>
      </AtFloatLayout>
      <Button className='commmon-btn' onClick={addAddress}>
        {type === 'edit' ? '编辑地址' : '添加地址'}
      </Button>
    </View>
  )
}

export default EditAndDelete
